<?php

namespace App\Http\Resources\CruiseCheck;

use App\Http\Resources\BaseResource;
use App\Http\Resources\Cruise\CruiseTemplateResource;
use App\Models\Cruise\CruiseCheckSelfDetailModel;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\MissingValue;

class SupplierTaskDetailResource extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        $notProduceCount = $this->when(
            $this->cruiseCheckSelfDetailRel,
            $this->cruiseCheckSelfDetailRel->where("status", CruiseCheckSelfDetailModel::STATUS_NOT_PRODUCE)->count(),
            0
        );

        return [
            "name"                     => $this->name,
            "taskStartTime"            => formatDateYmd($this->taskStartTime),
            "taskEndTime"              => formatDateYmd($this->taskEndTime),
            "executeStartHis"          => $this->executeStartHis,
            "executeEndHis"            => $this->executeEndHis,
            "templateId"               => $this->templateId,
            "templateDetail"           =>
                $this->when(
                    $this->resourceLoaded("cruiseTemplateRel"),
                    function () {
                        return CruiseTemplateResource::collection([$this->cruiseTemplateRel])
                                                     ->getIterator()
                                                     ->current();
                    },
                    new MissingValue()
                ),
            "totalCount"               => ($this->taskEndTime - $this->taskStartTime) / (24 * 60 * 60) + 1 - $notProduceCount,
            "cruiseCheckSelfDetailRel" =>
                $this->when(
                    $this->cruiseCheckSelfDetailRel,
                    function () {
                        return CruiseCheckSelfDetailListResource::collection(
                            $this->cruiseCheckSelfDetailRel
                                ->where("status", "<>", CruiseCheckSelfDetailModel::STATUS_NOT_PRODUCE)
                        );
                    },
                    []
                )
        ];
    }
}
